package com.hyt.it.ogt.common.config;

import com.hyt.core.constant.CommonConstant;
import com.hyt.core.enums.NumberEnum;
import com.hyt.it.ogt.common.config.serializable.FastJson2JsonRedisSerializer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
@EnableCaching
@Configuration
public class CacheConfig {

    @Resource
    RedisTemplate redisTemplate;

    @Bean
    public RedisCacheWriter writer() {
        return RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
    }

    @Bean
    @Primary
    public CacheManager cacheManager() {
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
        // 设置缓存管理器管理的缓存的默认过期时间
        defaultCacheConfig = defaultCacheConfig
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                // 设置value为json序列化
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new FastJson2JsonRedisSerializer(Object.class)))
                // 不缓存空值
                .disableCachingNullValues()
                // 缓存数据保存1分钟 （默认）
                .entryTtl(Duration.ofMinutes(CommonConstant.ONE));

        Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>();
        // 查询考试信息通过考试ID
        configurationMap.put(RedisKeyConstant.SELECT_EXAM_INFO_BY_EXAM_ID,
                RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(NumberEnum.FIVE.getK())));
        // 查询证书通过ID
        configurationMap.put(RedisKeyConstant.SELECT_ZS_INFO_BY_ID,
                RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(NumberEnum.FIVE.getK())));

        return RedisCacheManager.builder(writer())
                .cacheDefaults(defaultCacheConfig)
                .initialCacheNames(configurationMap.keySet())
                .withInitialCacheConfigurations(configurationMap)
                .build();
    }

}
